package club.jdiy.core.base;

import club.jdiy.core.AppContext;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 通用Controller代码基础类.
 *
 * @param <T>        Entity实体类名
 * @param <TService> 实体Service类名
 * @author ziquee(子秋) QQ号:39886616 主页: http://www.jdiy.club
 * @version 20200520
 */
@SuppressWarnings("ALL")

public abstract class JDiyCtrl<T, TService extends JDiyService> {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new Java8MyDateEditor(Java8MyDateEditor.Type.LocalDateTime));
        binder.registerCustomEditor(LocalDate.class, new Java8MyDateEditor(Java8MyDateEditor.Type.LocalDate));
        binder.registerCustomEditor(Double.class, new NumberEditor(NumberEditor.Type.Double));
        binder.registerCustomEditor(double.class, new NumberEditor(NumberEditor.Type.Double));
        binder.registerCustomEditor(Integer.class, new NumberEditor(NumberEditor.Type.Integer));
        binder.registerCustomEditor(int.class, new NumberEditor(NumberEditor.Type.Integer));
        binder.registerCustomEditor(Long.class, new NumberEditor(NumberEditor.Type.Long));
        binder.registerCustomEditor(long.class, new NumberEditor(NumberEditor.Type.Long));
    }

    @PostConstruct
    private void init() {
        if (this.service == null) {
            Class s = (Class<JDiyService>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
            this.service = (TService) context.getApplicationContext().getBean(s);
        }
    }

    protected TService service;

    @Resource
    protected AppContext context;
}
